package com.lcm.springcloud.controller;

import com.lcm.springcloud.common.ResultBean;
import com.lcm.springcloud.param.PaymentParam;
import com.lcm.springcloud.service.impl.PaymentServiceImpl;
import com.lcm.springcloud.vo.PaymentVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author: Coder-Lcm
 * @date: 2020/10/26 17:10
 */
@RestController
@Slf4j
@RequestMapping("/payment")
public class PaymentController {

    @Autowired
    PaymentServiceImpl paymentService;

    @Value("${server.port}")
    private String serverPort;

    /**
     * 用作服务发现：即对外暴露该服务提供者的信息
     */
    @Resource
    private DiscoveryClient discoveryClient;

    @GetMapping("/discovery")
    public Object discovery(){
        /**
         * 1. 获取服务清单列表
         */
        List<String> services = discoveryClient.getServices();
        services.forEach(each->{
            log.info("payment service element: " + each);
        });

        /**
         * 2. 根据服务名称获取服务实例
         */
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        instances.forEach(each->{
            log.info(each.getServiceId() + "\t" + each.getHost()+"\t" + each.getPort() + "\t" + each.getUri());
        });
        return this.discoveryClient;
    }

    @PostMapping("/add")
    public ResultBean addPayment(@RequestBody PaymentParam payment) {
        boolean ok = paymentService.addPayment(payment);
        if (ok){
            return new ResultBean(200, "添加成功！, serverPort" + serverPort);
        }
        return new ResultBean(444, "插入数据库失败！");
    }

    @GetMapping("/{id}")
    public ResultBean<PaymentVO> findById(@PathVariable("id") @NotNull @Min(1) Long id) {
        ResultBean<PaymentVO> bean = new ResultBean<>(200, "查询成功， serverPort" + serverPort);
        PaymentVO result = paymentService.findById(id);
        bean.setData(result);
        return bean;
    }

    /**
     * 用于测试自定义order80的负载均衡规则
     * @return
     */
    @GetMapping("/lb")
    public String getPaymentLB(){
        return serverPort;
    }

    @GetMapping("/feign/timeout")
    public String paymentFeignTimeout(){
        try{
            TimeUnit.SECONDS.sleep(3); //故意延时3秒
        }catch (InterruptedException e) {
            e.printStackTrace();
        }
        return serverPort;
    }

    /**
     * 用于测试zipkin + sleuth实现的链路调用监控
     * @return
     */
    @GetMapping("/zipkin")
    public String paymentZipkin(){
        return "Hi, l am payment zipkin server fall back ,welcome to lcmblog";
    }

}
